from mootdx.tools.reversion import reversion
from mootdx.quotes import Quotes
from db.save import Save
from db.read import DBReader
import numpy as np
from datetime import datetime
#除权除息数据落库
client = Quotes.factory(market="std")
read = DBReader()
stocklist=read.get_stock_list()

save = Save()
conn=save.connect()
cursor = conn.cursor()

for item in stocklist:
    stockcode = item[0]
    stockname = item[1]
    xdxr_data = client.xdxr(symbol=stockcode)
    for index_value, row_series in xdxr_data.iterrows():
        row_dict = row_series.to_dict()
        month=row_dict['month']
        day=row_dict['day']
        year = row_dict['year']
        monthstr = str(month)
        daystr = str(day)
        if month < 10:
            monthstr='0'+str(month)
        if day < 10:
            daystr = '0'+str(day)
        category = row_dict['category']
        categorystr = str(category)
        if category < 10:
            categorystr="0"+categorystr
        row_dict['date'] = str(year)+'-'+monthstr+'-'+daystr
        row_dict['id'] = str(year) + monthstr + daystr + categorystr + stockcode
        row_dict['stockcode'] = stockcode
        row_dict['stockname'] = stockname
        db_dict = {key: value for key, value in row_dict.items() if not (
            (isinstance(value, (float, np.float64)) and np.isnan(value)) or value is None)}

        save.exec(db_dict, "stock_cqcx_info", conn, cursor)

    print(str(datetime.now())+"save success: "+ stockcode +stockname)
cursor.close()
conn.close()
